package com.tanhua.admin.listener;

import com.tanhua.autoconfig.templates.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void audit(String movementId) throws Exception {
        System.out.println("获取消息movementId="+movementId);
        //1、根据动态id，查询动态,获取文本和图片内容
        Movement movement = movementApi.findById(movementId);
        if(movement != null && movement.getState() == 0) {
            String content = movement.getTextContent(); //文本内容
            List<String> medias = movement.getMedias(); //图片内容
            //2、调用工具类，审核文本，审核图片
            Map<String, String> textMap = template.greenTextScan(content);
            Map<String, String> picMap = template.imageScan(medias);
            String textSugg = textMap.get("suggestion");  //pass：成功
            String picSugg = picMap.get("suggestion");
            //3、更新数据库中的动态状态
            Integer state = 0; //待审核
            if(textSugg.equals("pass") && picSugg.equals("pass")) {
                state =1;//已通过
            }else if(textSugg.equals("block") || picSugg.equals("block")) {
                state =2; //内容违规
            }
            movementApi.updateState(movementId,state);
        }
    }
}
